<template>
  <div class="container">
    <div class='main' ref="hotproduct"></div>
    <div class="name" :style="styleMargin">{{pieName}}</div>
    <div class="icon iconfont icon-left" @click="handleClick(0)" :style="styleFontsize"></div>
    <div class="icon iconfont icon-right" @click="handleClick(1)" :style="styleFontsize"></div>
  </div>
</template>

<script>
import config from '@/config'
import {mapState} from 'vuex'

export default {
  name: 'Hotproduct',
  data() {
    return {
      chart: null,
      data: null,
      count: 0, // 当天饼图索引
      titleSize: 0, // 标题字体大小
      ws: null
    }
  },
  watch: {
    theme() {
      this.chart.dispose()
      this.initChart()
      this.updateChart()
       this.$nextTick(() => {
        this.adaptChart()
      })
    }
  },
  computed: {
    ...mapState(['theme']),
    pieName() {
      if (!this.data) return '女装'
      return this.data[this.count].name
    },
    styleFontsize() {
      return {
        fontSize: this.titleSize + 'px',
         color: config[this.theme].fontColor
      }
    },
    styleMargin() {
      return {
        fontSize: this.titleSize + 'px',
        marginRight: this.titleSize * 3 + 'px',
        marginBottom: this.titleSize + 'px',
         color: config[this.theme].fontColor
      }
    }
  },
  created() {
    this.ws = this.$ws.getInstance()
    // 注册回调函数 等服务器回应后调用
    this.ws.registerCallback('hotproductData', this.getData)
  },
  mounted() {
    this.initChart()
    // this.getData()
    this.ws.send(JSON.stringify({
      action: 'getData',
      socketType: 'hotproductData',
      chart: 'hotproduct',
      value: ''
    }))
    window.addEventListener('resize', this.adaptChart)
    this.adaptChart()

  },
  destroyed() {
    this.ws.unRegisterCallback('hotproductData')
    window.removeEventListener('resize', this.adaptChart)
  },
  methods: {
    initChart() {
      // 基于准备好的dom，初始化echarts实例
      this.chart = this.$echarts.init(this.$refs.hotproduct, this.theme)
      let option = {
        title: {
          left: 20,
          top: 20,
          text: '▎' + config.title['hotproduct'],

        },
        color: ['#0BA82C', '#2C6EFF', '#16F2D9', '#FE211E', '#FA6900', '#EEDD78'],
        legend: {
          left: 'center',
          top: '15%',
          show: true,
          icon: "circle"

        },
        grid: {
          top: '25%',
          left: '5%',
          right: '5%',
          bottom: '5%',
          containLabel: true
        },
        tooltip: {
          backgroundColor: 'rgba(50,50,50,0.7)',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          },
          formatter: arg => {
            let temp = arg.data.children
            let total = 0
            for (let i = 0; i < temp.length; i++) {
              total += temp[i].value
            }
            let str = ''
            let percent = 0
            for (let j = 0; j < temp.length; j++) {
              const element = temp[j]
              percent = (element.value / total * 100).toFixed(2) + '%'
              str += element.name + ': ' + percent + '<br />'
            }

            return str
          }
        },
        series: [
          {
            type: 'pie',    // 设置图表类型为饼图
            radius: '50%',  // 饼图的半径，外半径为可视区尺寸（容器高宽中较小一项）的 55% 长度。
            center: ['50%', '60%'],
            label: {
              show: false
            },
            emphasis: {
              label: {
                show: true,
                formatter: '{b} {d}%',
                color: 'inherit'
              },
              labelLine: {
                show: false
              }
            }
          }
        ]

      }
      // 绘制图表
      this.chart.setOption(option)
    },
    getData(data) {
      // let res = await getHotproduct()
      // this.data = res.data
      this.data = data
      this.updateChart()
    },
    updateChart() {
      let pie = this.data[this.count]
      let pieData = pie.children.map(item => {
        return item
      })
      let dataOption = {
        series: [
          {
            name: pie.name,
            data: pieData
          }
        ]
      }
      this.chart.setOption(dataOption)
    },
    adaptChart() {
      this.chart.resize()
      this.titleSize = this.$refs.hotproduct.offsetWidth / 100 * 3.6
      let adaptOption = {
        title: {
          textStyle: {
            fontSize: this.titleSize
          }
        },
        legend: {
          itemGap: this.titleSize / 2,
          itemWidth: this.titleSize,  // 设置宽度
          itemHeight: this.titleSize, // 设置高度
          textStyle: {
            fontSize: this.titleSize / 1.5,
          }
        }
      }
      // 绘制图表
      this.chart.setOption(adaptOption)
    },
    handleClick(num) {
      // 点击左箭头 0  点击右箭头1
      num == 1 ? this.count++ : this.count--
      this.count > this.data.length - 1 ? this.count = 0 : ''
      this.count < 0 ? this.count = this.data.length - 1 : ''
      this.updateChart()
    }
  }
}

</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped lang="scss">
.name {
  position: absolute;
  right: 10px;
  bottom: 10px;
  color: #fff;
}
.icon-left {
  position: absolute;
  left: 5%;
  top: 50%;
  color: #fff;
  font-size: 66px;
  cursor: pointer;
}

.icon-right {
  position: absolute;
  right: 5%;
  top: 50%;
  color: #fff;
  font-size: 66px;
  cursor: pointer;
}
</style>
